//
//  LoginViewController.m
//  Moko
//
//  Created by cj848 on 11. 7. 24..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "MokoAppDelegate.h"
@implementation LoginViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
-(void)setLoginVO:(LoginVO *)_loginVO {
    self.loginVO = _loginVO;
    [idTextField setText:loginVO._id];
    [passwordTextField setText:loginVO._password];
}

-(LoginVO*)loginVO{
    return self.loginVO;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    if( textField.tag == 1 ) {
        [self login:textField];
    }
    return YES;
}
- (void)dealloc
{
    [idTextField release];
    [passwordTextField release];
    [loginVO release];
    [loginButton release];
    [guestButton release];
    [loginView release];
    [autoLoginSwitch release];
    [super dealloc];
}
- (IBAction)login:(id)sender {
    NSString* idstr = [idTextField text];
    NSString* password = [passwordTextField text];
    if( [idstr length] == 0 || [password length] == 0 ) {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"입력값을 확인해 주세요." message:@"ID 및 패스워드는 필수 입력 사항입니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [alertView show];
        [alertView release];
        return;
    }
    GET_APPDELEGATE;
    NSString* action = [NSString stringWithFormat:@"%@/zboard4/login_check.php?user_id=%@&password=%@", delegate.configVO.siteHostAddress, idstr, password];
    [delegate.httpClient requestURL:action httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}

- (IBAction)guest:(id)sender {
    GET_APPDELEGATE;
    delegate.configVO.autoLogin = [NSNumber numberWithBool:autoLoginSwitch.on];
    delegate.configVO.username = idTextField.text;
    delegate.configVO.password = passwordTextField.text;
    NSError* saveError;
    [delegate.managedObjectContext save:&saveError];
    [self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    //loginView.logoImage = [UIImage imageNamed:@"seeko_logo1.png"];
    loginView.logoImage = [UIImage imageNamed:@"login_background.png"];
    GET_APPDELEGATE;
    autoLoginSwitch.on = [delegate.configVO.autoLogin boolValue];
    idTextField.text = delegate.configVO.username;
    passwordTextField.text = delegate.configVO.password;
}
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}


- (void)viewDidUnload
{
    [guestButton release];
    guestButton = nil;	
    [loginView release];
    loginView = nil;
    [autoLoginSwitch release];
    autoLoginSwitch = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSArray* subviews = [self.view subviews];
    for( UIView* views in subviews ) 
        [views resignFirstResponder];
}

-(void)finishLoading:(NSData *)data {
    GET_APPDELEGATE;
    BOOL isLogined = NO;
    NSString* username = nil;
    NSArray* cookies = delegate.httpClient._cookies;
    for( NSHTTPCookie *cookie in cookies ) {
        if( [[cookie name] isEqualToString:@"user[id]"] ) {
            isLogined = YES;
        }
        else if ([[cookie name] isEqualToString:@"user[name]"]) {
            isLogined = YES;
            username = [[[cookie value] stringByReplacingOccurrencesOfString:@"+" withString:@"%20"] stringByReplacingPercentEscapesUsingEncoding:EUC_KR];
        }
    }
    delegate.httpClient.isLogin = isLogined;
    delegate.configVO.autoLogin = [NSNumber numberWithBool:autoLoginSwitch.on];
    if( !isLogined) {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"잘못된 ID or Password" message:@"올바른 로그인 정보를 입력해 주세요" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [alertView show];
        [alertView release];
        return;
    }
    else {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"로그인 되었습니다." message:[NSString stringWithFormat:@"%@님 환영합니다.\n올바르게 로그인 되었습니다.", username] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        // 로그인이 되어 있고 자동 로그인으로 설정 되어있을때만 유저 정보 저장
        if( autoLoginSwitch.on == YES ) {
            delegate.configVO.username = idTextField.text;
            delegate.configVO.password = passwordTextField.text;
        }
        [alertView show];
        [alertView release];
    }
    NSError* saveError;
    if( [delegate.managedObjectContext save:&saveError] == YES ) {
        NSLog(@"saved loginInfo");
    }
    [self dismissModalViewControllerAnimated:YES];
}


@end
